<template>
  <div class="purchase-detail">
    <!-- 顶部导航 -->
    <van-nav-bar
      title="求购详情"
      left-arrow
      @click-left="onClickLeft"
      fixed
      placeholder
      safe-area-inset-top
    />

    <!-- 商家信息 -->
    <div v-if="type === '1'" class="merchant-info">
      <div class="merchant-header">
        <div class="avatar">
          <img :src="merchantInfo?.headUrl || avatar" alt="avatar" />
          <p class="auth" v-if="merchantInfo?.authType == 1">实名认证</p>
        </div>
        <div class="merchant-content">
          <div class="merchant-name">
            {{ merchantInfo?.userCompanyAuthDTO?.companyName || merchantInfo.userName }}
          </div>
          <div class="merchant-tags">
            <span class="tag van-hairline--surround crown"
              >{{ purchaseData.vipTime }}年{{ getVipLevel }}</span
            >
            <span
              class="tag van-hairline--surround verify"
              v-if="merchantInfo?.companyAuthType == 1"
              >企业认证</span
            >
          </div>
          <div class="rating-stars">
            <van-rate
              v-model="rating"
              :size="16"
              color="#32BC05"
              void-icon="star"
              void-color="#eee"
              readonly
            />
            <div class="recent-purchase">近期求购：{{ pullNum }}单</div>
          </div>
        </div>
      </div>
      <div class="merchant-address">
        <van-icon name="location-o" />
        <div class="address" v-if="merchantInfo?.companyAuthType == 1">
          {{
            `${merchantInfo?.userCompanyAuthDTO?.province}${merchantInfo?.userCompanyAuthDTO?.city}${merchantInfo?.userCompanyAuthDTO?.district}${merchantInfo?.userCompanyAuthDTO?.address}`
          }}
        </div>
        <span class="distance">900km</span>
      </div>
      <div class="merchant-actions van-hairline--top">
        <div class="fans">
          <van-icon
            @click="handleFavorite"
            :name="merchantInfo?.favoriteStoreState ? 'like' : 'like-o'"
          />
          <span>粉丝{{ merchantInfo.storeBeFavoriteNum }}</span>
        </div>
        <van-button type="primary" color="#32BC05" class="contact-btn" round @click="handlePhone"
          >联系苗商</van-button
        >
      </div>
    </div>

    <!-- 求购信息 -->
    <div class="purchase-info">
      <div class="info-item">
        <div class="label">求购品种</div>
        <div class="value">{{ purchaseData.title }}</div>
      </div>
      <div class="info-item">
        <div class="label">求购数量</div>
        <div class="value">{{ purchaseData.pullNum }}株</div>
      </div>
      <div class="info-item specs">
        <div class="label">求购规格</div>
        <div class="value">
          <div
            class="spec-item"
            v-for="(item, index) in purchaseData.attributeDocuments"
            :key="index"
          >
            {{ item.attributeName }}：{{ item.minValue }}-{{ item.maxValue }}{{ item.unit }}
          </div>
        </div>
      </div>
      <div class="info-item">
        <div class="label">求购期限</div>
        <div class="value">{{ purchaseData.pullTime }}天</div>
      </div>
      <div class="info-item">
        <div class="label">用苗地</div>
        <div class="value">{{ purchaseData.receiveProvince + purchaseData.receiveCity }}</div>
      </div>
      <div class="info-item" v-if="purchaseData.deliverProvince">
        <div class="label">期望货源</div>
        <div class="value">
          {{ `${purchaseData.deliverProvince}${purchaseData.deliverProvince}` }}
        </div>
      </div>
      <div class="info-item" v-if="purchaseData?.createTime">
        <div class="label">发布日期</div>
        <div class="value">{{ purchaseData.createTime.slice(0, 10) }}</div>
      </div>
      <div class="info-item description" v-if="purchaseData.remark">
        <div class="label">求购描述</div>
        <div class="value">{{ purchaseData.remark }}</div>
      </div>
      <div class="info-item images" v-if="purchaseData.ossUrls">
        <div class="label">求购图片</div>
        <div class="value">
          <van-image
            width="100%"
            height="100%"
            v-for="item in purchaseData.ossUrls.split(',')"
            :src="item"
          />
        </div>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="footer" v-if="type === '1'">
      <van-button color="#32BC05" block round @click="handlePhone">联系他</van-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import webView from '@/utils/webView.js' //给安卓使用
import { Hybrid } from '@/utils/hybrid'
import { getDeviceType } from '@/utils/tools'
import bridge from '@/utils/bridge'
import {
  pullProductGetById,
  getMerchantInfo,
  latelyPullNum,
  favorite,
  unFavorite,
  getCompanyContactPhone
} from '@/api'
import { ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import avatar from '@/assets/avatar.png'

// 区分不同来源，从搜索进入求购详情需要展示企业信息和联系
const type = ref('')
const router = useRouter()
const route = useRoute()
const rating = ref(5)
const purchaseData = ref({})
const merchantInfo = ref({})
const pullNum = ref(0)
const phone = ref('')
const locationLng = ref('')
const locationLat = ref('')
const info = ref({})

// 获取会员等级
const getVipLevel = computed(() => {
  if (merchantInfo.value.vipLevelCode == 'v0') {
    return '普通会员'
  } else if (merchantInfo.value.vipLevelCode == 'v1') {
    return '个人会员'
  } else if (merchantInfo.value.vipLevelCode == 'v2') {
    return '企业会员'
  } else if (merchantInfo.value.vipLevelCode == 'v3') {
    return '白金会员'
  } else if (merchantInfo.value.vipLevelCode == 'v4') {
    return '钻石会员'
  } else if (merchantInfo.value.vipLevelCode == 'v5') {
    return '皇冠会员'
  }
})

const onClickLeft = () => {
  router.back()
}

const getDetailInfo = async () => {
  const { code, data } = await pullProductGetById({
    pullProductId: route.query.pullProductId
  })
  if (code === 200) {
    purchaseData.value = data
  }
}

// 苗商信息
const getMxInfo = async () => {
  await getLocation()
  let { code, data } = await getMerchantInfo({
    userId: purchaseData.value.userId,
    locationLng: info.value.lng,
    locationLat: info.value.lat
  })
  if (code === 200) {
    merchantInfo.value = data
  }
}

// 获取苗商电话
const getPhone = async () => {
  let { code, data } = await getCompanyContactPhone({
    userId: merchantInfo.value.userId
  })
  if (code === 200) {
    phone.value = data
  }
}

const getLatelyPullNum = async () => {
  let { code, data } = await latelyPullNum()
  if (code === 200) {
    pullNum.value = data
  }
}

// 收藏取消苗商
const handleFavorite = async () => {
  let res = null
  if (merchantInfo.value.favoriteStoreState) {
    res = await unFavorite({
      type: 'store',
      relevanceId: merchantInfo.value?.userId
    })
  } else {
    res = await favorite({
      type: 'store',
      relevanceId: merchantInfo.value?.userId
    })
  }
  if (res.code === 200) {
    getMxInfo()
  }
}

onMounted(async () => {
  // 隐藏原生导航
  bridge.setNavigationBarVisible({
    value: '0'
  })
  type.value = route.query.type
  getLatelyPullNum()
  await getDetailInfo()
  await getMxInfo()
})

// 获取定位
const getLocation = async () => {
  const deviceType = getDeviceType()
  if (deviceType === 'android') {
    webView.getLocation((location) => {
      locationLng.value = location.lng
      locationLat.value = location.lat
      console.log('location:', location)
    })
  } else {
    Hybrid.getLocation()
      .then((location) => {
        locationLng.value = location.lng
        locationLat.value = location.lat
        console.log('location:', location)
      })
      .catch((error) => {
        console.error('获取用户定位信息失败:', error)
      })
  }
}

// 拨打电话
const handlePhone = async () => {
  if (phone.value) {
    bridge.phoneFunc({ value: phone.value })
  } else {
    await getPhone()
    bridge.phoneFunc({ value: phone.value })
  }
}
</script>

<style lang="scss" scoped>
.purchase-detail {
  min-height: 100vh;
  background: #f7f8fa;
  padding-bottom: 80px;

  :deep(.van-nav-bar) {
    .van-nav-bar__title {
      color: #222;
      font-weight: 400;
    }
    .van-icon {
      color: #222;
    }
  }

  .merchant-info {
    padding: 16px 10px 4px;
    background: linear-gradient(180deg, #edfef4 0%, #ffffff 47%);

    .merchant-header {
      display: flex;
      margin-bottom: 12px;

      .avatar {
        position: relative;
        img {
          display: block;
          width: 50px;
          height: 50px;
          border-radius: 50%;
          margin-right: 10px;
        }
        .auth {
          position: absolute;
          top: 43px;
          font-size: 10px;
          color: #fff;
          background: #c8933b;
          line-height: 16px;
          width: 50px;
          text-align: center;
          border-radius: 25px;
        }
      }

      .merchant-content {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-between;

        .merchant-name {
          font-size: 15px;
          font-weight: 400;
          color: #222;
          margin-bottom: 5px;
        }

        .merchant-tags {
          margin-bottom: 5px;
          .tag {
            display: inline-block;
            padding: 2px 6px;
            border-radius: 4px;
            font-size: 10px;
            margin-right: 8px;
            line-height: 18px;
            padding: 0 5px;

            &.crown {
              color: #d65858;
              border-color: #d65858;
            }

            &.verify {
              color: #c8933b;
              border-color: #c8933b;
            }

            &.van-hairline--surround:after {
              border-radius: 18px;
            }
          }
        }

        .rating-stars {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .recent-purchase {
            color: #222222;
            font-size: 11px;
          }
        }
      }
    }

    .merchant-address {
      display: flex;
      align-items: baseline;
      justify-content: space-between;
      font-size: 12px;
      margin-bottom: 12px;
      color: #666;

      .van-icon {
        margin-right: 4px;
        color: #969799;
      }

      .address {
        margin-right: 8px;
        flex: 1;
        text-align: left;
        line-height: 20px;
      }

      .distance {
        color: #969799;
      }
    }

    .merchant-actions {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 36px;

      .fans {
        display: flex;
        align-items: center;
        color: #666666;
        font-size: 12px;

        .van-icon {
          margin-right: 4px;
          color: #969799;
        }
      }

      .contact-btn {
        padding: 0;
        width: 80px;
        height: 28px;
        font-size: 14px;
        color: #fff;
        a {
          color: #fff;
        }
      }
    }
  }

  .purchase-info {
    margin-top: 10px;
    padding: 16px;
    background: #fff;

    .info-item {
      display: flex;
      margin-bottom: 16px;
      line-height: 17px;

      .label {
        width: 80px;
        color: #666;
        font-size: 12px;
      }

      .value {
        flex: 1;
        color: #222;
        font-size: 12px;
      }

      &.specs {
        .value {
          .spec-item {
            margin-bottom: 8px;

            &:last-child {
              margin-bottom: 0;
            }
          }
        }
      }

      &.description {
        .value {
          line-height: 1.5;
        }
      }

      &.images {
        .value {
          display: flex;
          flex-wrap: wrap;
          gap: 8px;
        }
      }
    }
  }

  .footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 16px;
    background: #fff;
    box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.06);
    a {
      color: #fff;
    }
  }
}
</style>
